package com.example.personblog.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController{
    @PostMapping("/upload")
    public String up(String nickname, MultipartFile photo, HttpServletRequest request)throws IOException{
        System.out.println(nickname);
        //获得图片原始名称
        System.out.println(photo.getOriginalFilename());
        //获取文件类型
        System.out.println(photo.getContentType());
        //获取web服务器的运行目录,程序最终放在云端,liunex服务器上,所以需要动态的获取
        //HttpServletRequest request是javaee类自带的类,可以获取前端的请求

        //通过web服务器得到运行的路径,控制台显示出来的tomcat.........路径是idea自己分配的
        String path=request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        //自定义方法,把文件存起来
        saveFile(photo,path);
        return "上传成功";
    }
    public void saveFile(MultipartFile photo,String path)throws IOException{
        //判断存储的目录是否存在,如果不存在则创建
        File dir=new File(path);
        if (!dir.exists()){
            //创建目录
            dir.mkdir();
        }

        File file=new File(path+photo.getOriginalFilename());
        photo.transferTo(file);
    }
}
